package com.ts.api.http.receive.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.context.ApiContext;
import com.ts.api.common.util.ApiDictUtils;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.http.receive.entity.apply.req.ApiReceiveApplyLiXiangHua;
import com.ts.api.http.receive.entity.dataexchange.req.ApiReceiveDataExchangeLiXiangHua;
import com.ts.api.module.api.convert.core.annotation.ApiReceive;
import com.ts.api.module.api.convert.core.annotation.ApiReceiveConvertType;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveApply;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveDecrypt;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveNotice;
import com.ts.api.module.api.convert.receive.entity.ApiReceivePhoneMd5DataExchange;
import com.ts.api.module.api.convert.receive.handler.ApiReceivePhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;

import java.util.Map;

/**
 * 理享花
 *
 * https://apifox.com/apidoc/shared-344ad4ea-8455-4c62-a65c-8bf2489bf8a3?pwd=vDD3PXd2
 *
 * @author WJB
 */
@ApiReceive(apiClientId = "1930558812213628928",type = ApiReceiveConvertType.API_CHANNEL_PHONE_MD5)
public class ApiReceivePhoneMd5LiXiangHua implements ApiReceivePhoneMd5ConvertHandler {

    private static String KEY = "abcdef0123456789";

    @Override
    public Map<String, String> requireParam(RequestVO requestVO) throws Exception {
        //  获取请求体参数
        Map<String, Object> map = JsonUtils.toMap(requestVO.getBody());

        //  传递什么，验证什么Key
        String data = String.valueOf(map.get("data"));
        String channelNum = String.valueOf(map.get("channelNum"));
        Assert.isNotEmptyThrows(data, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("data")));
        Assert.isNotEmptyThrows(channelNum, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("channelNum")));
        //  返回需要的数据Map
        return MapUtils.newHashMap(newMap -> {
            newMap.put("data", data);
            newMap.put("channelNum", channelNum);
        });
    }

    @Override
    public ApiReceiveDecrypt decrypt(Map<String, String> paramMap, RequestVO requestVO) throws Exception {
        String content = paramMap.get("data");

        //  文档解密过程
        AES ecb = AES.createEcb(KEY.getBytes());
        String decrypt = ecb.decryptFromBase64Str(content);
        return new ApiReceiveDecrypt(decrypt);
    }

    @Override
    public ApiUserRequest parseDataExchange(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveDataExchangeLiXiangHua parse = apiReceiveDecrypt.parse(ApiReceiveDataExchangeLiXiangHua.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respDataExchange(ApiReceivePhoneMd5DataExchange dataExchangeMessage) throws Exception {

        boolean suc = dataExchangeMessage.hasBizSuc();

        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", 500);
            resultMap.put("msg", dataExchangeMessage.getBizMsg());
            return resultMap;
        }

        //成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", 200);
        resultMap.put("msg", "匹配成功");
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
            //  撞库成功时生成的唯一订单号，进件申请时需要
            dataMap.put("orderId", ApiContext.REQ_ID.get());
            //  机构名称
            dataMap.put("companyName", dataExchangeMessage.getOrgName());
            //  产品名称
            dataMap.put("productName", dataExchangeMessage.getDisplayName());
            //  分润前价格
            dataMap.put("price", dataExchangeMessage.getPrice());
            //  跳转链接
            dataMap.put("url", dataExchangeMessage.getCallUrl());
            //  logo
            dataMap.put("logo", dataExchangeMessage.getLogoPath());
        }));
        return resultMap;
    }

    @Override
    public ApiUserRequest parseApply(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveApplyLiXiangHua parse = apiReceiveDecrypt.parse(ApiReceiveApplyLiXiangHua.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respApply(ApiReceiveApply applyMessage) throws Exception {
        boolean suc = applyMessage.hasBizSuc();

        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", 500);
            resultMap.put("msg", applyMessage.getBizMsg());
            return resultMap;
        }

        // 成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", 200);
        resultMap.put("msg", "进件成功");
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap2 -> {

        }));
        return resultMap;
    }

    @Override
    public void fieldMapping(ApiUserRequest apiUserRequest) {

        // sex 性别 0-女 1-男
        // sex 性别
        // 0 男
        // 1 女
        // 2 未知
        String sex = apiUserRequest.getSex();
        if (ValidParam.isNotEmpty(sex)) {
            String sexChoose = ChooseEq.create()
                    .when(sex, "0", "1")
                    .when(sex, "1", "0")
                    .end("1");
            apiUserRequest.setSex(sexChoose);
        }


        // sesame 芝麻分 1、无芝麻分 2、600分以下 3、600-650分 4、650-700分 5、700分以上 默认2
        // sesameCredit 芝麻分
        // 1 600分以下
        // 2 600~649分
        // 3 650~699分
        // 4 700分以上
        String sesameCredit = apiUserRequest.getSesameCredit();
        if (ValidParam.isNotEmpty(sesameCredit)) {
            String value = ChooseEq.create()
                    .when(sesameCredit, "1", "1")
                    .when(sesameCredit, "2", "1")
                    .when(sesameCredit, "3", "2")
                    .when(sesameCredit, "4", "3")
                    .when(sesameCredit, "5", "4")
                    .end();
            apiUserRequest.setSesameCredit(value);
        }

        // accumulationFund 公积金 1-无公积金 2-6个月以下 3-6个月以上 默认1
        // providentFund 公积金
        // 1 无公积金
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有公积金
        String providentFund = apiUserRequest.getProvidentFund();
        if (ValidParam.isNotEmpty(providentFund)) {
            String value = ChooseEq.create()
                    .when(providentFund, "1", "1")
                    .when(providentFund, "2", "2")
                    .when(providentFund, "3", "3")
                    .end();
            apiUserRequest.setProvidentFund(value);
        }

        // social 社保 1-无社保 2-6个月以下 3-6个月以上 默认1
        // socialSecurity 社保缴纳
        // 1 无社保
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有社保
        String socialSecurity = apiUserRequest.getSocialSecurity();
        if (ValidParam.isNotEmpty(socialSecurity)) {
            String value = ChooseEq.create()
                    .when(socialSecurity, "1", "1")
                    .when(socialSecurity, "2", "2")
                    .when(socialSecurity, "3", "3")
                    .end();
            apiUserRequest.setSocialSecurity(value);
        }

        // insurance 保单 1-无保单 2-有保单 默认1
        // insurancePolicy 保险保单
        // 1 无保险保单
        // 2 缴纳未满1年
        // 3 缴纳1年以上
        // 4 有保险保单
        String insurancePolicy = apiUserRequest.getInsurancePolicy();
        if (ValidParam.isNotEmpty(insurancePolicy)) {
            String value = ChooseEq.create()
                    .when(insurancePolicy, "1", "1")
                    .when(insurancePolicy, "2", "4")
                    .end();
            apiUserRequest.setInsurancePolicy(value);
        }

        // house 房产情况 1-无 2-有 默认1
        // realEstateInfo 房产情况
        // 1 无房产
        // 2 有房不抵押
        // 3 有房可抵押
        // 4 有房产
        // 5 有按揭房产
        // 6 有全款房产
        String realEstateInfo = apiUserRequest.getRealEstateInfo();
        if (ValidParam.isNotEmpty(realEstateInfo)) {
            String value = ChooseEq.create()
                    .when(realEstateInfo, "1", "1")
                    .when(realEstateInfo, "2", "4")
                    .end();
            apiUserRequest.setRealEstateInfo(value);
        }

        // car 车产 1-无 2-有 默认1
        // carInfo 车辆情况
        // 1 无车产
        // 2 有车不抵押
        // 3 有车可抵押
        // 4 有车产
        String carInfo = apiUserRequest.getCarInfo();
        if (ValidParam.isNotEmpty(carInfo)) {
            String value = ChooseEq.create()
                    .when(carInfo, "1", "1")
                    .when(carInfo, "2", "4")
                    .end();
            apiUserRequest.setCarInfo(value);
        }

        // profession 职业 1-上班族 2-公务员/事业单位 3-私营业主 4-个体户 5-其他 默认1
        // career
        //   1	上班族
        //   2	自由职业
        //   3	企业主（有营业执照）
        //   4	公务员或事业单位
        //   5	个体户
        String career = apiUserRequest.getCareer();
        if (ValidParam.isNotEmpty(career)) {
            String value = ChooseEq.create()
                    .when(career, "1", "1")
                    .when(career, "2", "4")
                    .when(career, "3", "3")
                    .when(career, "4", "5")
                    .when(career, "4", "2")
                    .end();
            apiUserRequest.setCareer(value);
        }

        // loadAmount 借款金额 直接数字
        // loanAmount 贷款金额
        // 1 3万以下
        // 2 5万-10万
        // 3 10万-20万
        // 4 20万以上
        String loanAmount = apiUserRequest.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            apiUserRequest.setLoanAmount(ApiDictUtils.convertLoanAmount(loanAmount, true));
        }

        // loanUse 借款用途 1：购房 2：购车 3：住房装修 4：教育深造 5：休闲旅游 6：个人消费 7：房租缴纳 8：其他贷款 默认6
        // loanPurpose
        // 1 旅游
        // 2 教育
        // 3 婚庆
        // 4 装修
        // 5 医疗
        // 6 个人消费
        String loanPurpose = apiUserRequest.getLoanPurpose();
        if (ValidParam.isNotEmpty(loanPurpose)) {
            String value = ChooseEq.create()
                    .when(loanPurpose, "1", "6")
                    .when(loanPurpose, "2", "6")
                    .when(loanPurpose, "3", "4")
                    .when(loanPurpose, "4", "2")
                    .when(loanPurpose, "5", "1")
                    .when(loanPurpose, "6", "6")
                    .when(loanPurpose, "7", "6")
                    .when(loanPurpose, "8", "6")
                    .end();
            apiUserRequest.setLoanPurpose(value);
        }

        // creditCard 信用卡 1:无信用卡 2:1万以下 3:1-5万 4:5万以上 默认1
        // creditLimit 信用卡额度
        // 1 无信用卡
        // 2 3千以下
        // 3 3千-1万
        // 4 1-3万
        // 5 3万以上
        // 6 有信用卡
        String creditLimit = apiUserRequest.getCreditLimit();
        if (ValidParam.isNotEmpty(creditLimit)) {
            String value = ChooseEq.create()
                    .when(creditLimit, "1", "1")
                    .when(creditLimit, "2", "3")
                    .when(creditLimit, "3", "4")
                    .when(creditLimit, "4", "5")
                    .end();
            apiUserRequest.setCreditLimit(value);
        }

        // whiteBar 白条 1:无白条 2:1万以下 3:1-5万 4:5万以上 默认1
        // btLimit 京东白条可用额度
        // 1 无额度
        // 2 3千以下
        // 3 3千-1万
        // 4 1-3万
        // 5 3万以上
        String btLimit = apiUserRequest.getBtLimit();
        if (ValidParam.isNotEmpty(btLimit)) {
            String value = ChooseEq.create()
                    .when(btLimit, "1", "1")
                    .when(btLimit, "2", "3")
                    .when(btLimit, "3", "4")
                    .when(btLimit, "4", "5")
                    .end();
            apiUserRequest.setBtLimit(value);
        }

        // flowers 花呗 1:无花呗 2:1万以下 3:1-5万 4:5万以上 默认1
        // hbLimit 蚂蚁花呗可用额度
        // 1 无额度
        // 2 3千以下
        // 3 3千-1万
        // 4 1-3万
        // 5 3万以上
        String hbLimit = apiUserRequest.getHbLimit();
        if (ValidParam.isNotEmpty(hbLimit)) {
            String value = ChooseEq.create()
                    .when(hbLimit, "1", "1")
                    .when(hbLimit, "2", "3")
                    .when(hbLimit, "3", "4")
                    .when(hbLimit, "4", "5")
                    .end();
            apiUserRequest.setHbLimit(value);
        }

        // education 学历 1:大专以下 2:大专 3:本科 4:研究生及以上 默认2
        // educationAttainment 学历
        // 1 初中及以下
        // 2 中专
        // 3 高中
        // 4 大专
        // 5 本科
        // 6 研究生及以上
        String educationAttainment = apiUserRequest.getEducationAttainment();
        if (ValidParam.isNotEmpty(educationAttainment)) {
            String value = ChooseEq.create()
                    .when(educationAttainment, "1", "3")
                    .when(educationAttainment, "2", "4")
                    .when(educationAttainment, "3", "5")
                    .when(educationAttainment, "4", "6")
                    .end();
            apiUserRequest.setEducationAttainment(value);
        }
    }

    @Override
    public Object reqPullApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return MapUtils.newHashMap(newMap -> newMap.put("orderId", apiReceiveNotice.getReqId()));
    }

    @Override
    public boolean respPullApplyNotice(String responseBody) {
        JSONObject jsonObject = JsonUtils.get(responseBody);
        Integer code = jsonObject.getInteger("code");
        return Eq.object(code, 200);
    }

    @Override
    public Object reqPushApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return MapUtils.newHashMap(newMap -> newMap.put("orderId", apiReceiveNotice.getReqId()));
    }

    @Override
    public boolean respPushApplyNotice(String responseBody) {
        JSONObject jsonObject = JsonUtils.get(responseBody);
        Integer code = jsonObject.getInteger("code");
        return Eq.object(code, 200);
    }
}
